package com.lc.railway.ui.dialog;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.HttpMethod;
import com.hjq.permissions.Permission;
import com.hjq.toast.ToastUtils;
import com.lc.base.BaseDialog;
import com.lc.railway.R;
import com.lc.railway.aop.CheckNet;
import com.lc.railway.aop.Permissions;
import com.lc.railway.aop.SingleClick;
import com.lc.railway.other.AppConfig;

import java.io.File;

import androidx.core.content.FileProvider;

public final class UpdateNewsDialog {
    public static final class Builder
            extends BaseDialog.Builder<UpdateDialog.Builder> {

        private Context context;
        private final ProgressBar mProgressView;

        private final TextView mUpdateView;
        private final TextView mCloseView;

        /** Apk 文件 */
        private File mApkFile;
        /** 下载地址 */
        private String mDownloadUrl;


        /** 当前是否下载中 */
        private boolean mDownloading;
        /** 当前是否下载完毕 */
        private boolean mDownloadComplete;

        public Builder(Context context) {
            super(context);
           this.context=context;
            setContentView(R.layout.updatenews_dialog);
            setAnimStyle(BaseDialog.ANIM_BOTTOM);
            setCancelable(false);


            mProgressView = findViewById(R.id.pb_update_progress);
            mUpdateView = findViewById(R.id.tv_update_update);
            mCloseView = findViewById(R.id.tv_update_close);
            setOnClickListener(mUpdateView, mCloseView);
        }







        /**
         * 设置下载 url
         */
        public UpdateNewsDialog.Builder setDownloadUrl(String url) {
            mDownloadUrl = url;
            return this;
        }


        @SingleClick
        @Override
        public void onClick(View view) {
            if (view == mCloseView) {
                dismiss();
            } else if (view == mUpdateView) {
                // 判断下载状态
                if (mDownloadComplete) {
                    if (mApkFile.isFile()) {
                        ToastUtils.show("请在Download文件中查看下载文件");
//                        openFile();
                       dismiss();
                    } else {
                        // 下载失败，重新下载
                        downloadApk();
                    }
                } else if (!mDownloading) {
                    // 没有下载，开启下载
                    downloadApk();
                }
            }
        }

        /**
         * 下载 Apk
         */
        @CheckNet
        @Permissions({Permission.MANAGE_EXTERNAL_STORAGE})
        private void downloadApk() {
            // 设置对话框不能被取消
            setCancelable(false);


            // 创建要下载的文件对象
            mApkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    getString(R.string.app_name) + "文件");
            EasyHttp.download(getDialog())
                    .method(HttpMethod.GET)
                    .file(mApkFile)
                    .url(mDownloadUrl)
                    .listener(new OnDownloadListener() {

                        @Override
                        public void onStart(File file) {
                            // 标记为下载中
                            mDownloading = true;
                            // 标记成未下载完成
                            mDownloadComplete = false;
                            // 后台更新
                            mCloseView.setVisibility(View.GONE);
                            // 显示进度条
                            mProgressView.setVisibility(View.VISIBLE);
                            mUpdateView.setText(R.string.update_status_start);
                        }

                        @Override
                        public void onProgress(File file, int progress) {
                            mUpdateView.setText(String.format(getString(R.string.update_status_running), progress));
                            mProgressView.setProgress(progress);

                        }

                        @Override
                        public void onComplete(File file) {

                            mUpdateView.setText(R.string.update_status_successful);
                            // 标记成下载完成
                            mDownloadComplete = true;

                        }

                        @SuppressWarnings("ResultOfMethodCallIgnored")
                        @Override
                        public void onError(File file, Exception e) {
                            // 清除通知

                            mUpdateView.setText(R.string.update_status_failed);
                            // 删除下载的文件
                            file.delete();
                        }

                        @Override
                        public void onEnd(File file) {
                            // 更新进度条
                            mProgressView.setProgress(0);
                            mProgressView.setVisibility(View.GONE);
                            // 标记当前不是下载中
                            mDownloading = false;

                        }

                    }).start();
        }

        private void openFile() {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(getContext(), AppConfig.getPackageName() + ".provider", mApkFile);

            } else {
                uri = Uri.fromFile(mApkFile);
            }
            String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(uri.toString());
            String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            intent.setDataAndType(uri,mimetype);
            context.startActivity(intent);

        }

    }


}
